package com.softeem.springboot02generator.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.softeem.springboot02generator.entity.User;
import com.softeem.springboot02generator.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录  http://127.0.0.1:8081/login?username=用户名&password=密码
     *
     * @param username
     * @param password
     * @return
     */
//    @RequestMapping(value = "/login", method = RequestMethod.GET)
//    public String login(String username, String password) {
//        if (Objects.equals(username, "admin") && Objects.equals(password, "123456")) {
//            return "登录成功";
//        }
//        return "账号或密码错误";
//    }
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
        if (Objects.isNull(user)) {
            return "用户不存在";
        }
        // 验证密码
        if (!Objects.equals(user.getPassword(), password)) {
            return "密码错误";
        }
        return "登录成功";
    }
    /**
     * 用户注册： http://127.0.0.1:8081/reg?username=用户名&password=密码
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String reg(String username, String password) {
        //根据用户名查询用户  select * from user where username=?
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
        if (Objects.nonNull(user)) {
            return "该用户已存在";
        }
        user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int i = userMapper.insert(user);
        return i > 0 ? "注册成功" : "注册失败";
    }

}
